package Class.Handler;

import Class.Handler.*;
import Class.Dialog.*;
import Class.TextWindow.*;
import Class.Main.*;

import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

//
public class TextAreaHandler implements DocumentListener , CaretListener{
    private TextWindow textWindow;

    public TextAreaHandler(TextWindow textWindow){
        this.textWindow=textWindow;
    }

    //插入内容自动回调
    @Override
    public void insertUpdate(DocumentEvent e) {
        processContChange();
    }

    private void processContChange() {
        //给标题加上星号
        String title = textWindow.getTitle();
        if(title.startsWith("*")){
            return;
        }
        textWindow.setTitle("*"+title);
        textWindow.setHasSaved(false);
    }

    //删除内容自动回调
    @Override
    public void removeUpdate(DocumentEvent e) {
        processContChange();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {

    }

    @Override
    public void caretUpdate(CaretEvent e) {
        JTextArea textArea = textWindow.getTextArea();
        int caretPosition = textArea.getCaretPosition();
        int line = 1;
        int row = 1;
        try {
            //通过偏移量（下标）获取行号，参数和返回值从0开始
            line = textArea.getLineOfOffset(caretPosition)+1;
            //获取行首偏移量（下标）
            row = caretPosition-textArea.getLineStartOffset(line-1)+1;
        } catch (BadLocationException ex) {
            throw new RuntimeException(ex);
        }
        textWindow.getStatusLabel().setText("|第"+line+"行，第"+row+"列|");
    }
}
